package org.dousb.doujcodesandbox.utils;


import cn.hutool.core.date.StopWatch;
import org.dousb.doujcodesandbox.model.ExecuteMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * ProcessUtils
 *
 * @author 豆沙包
 * @version 1.0
 * @since 2025-11-02  15:14
 */
public class ProcessUtils {

    /**
     * 执行命令
     *
     * @param process
     * @param opName
     * @return
     * @throws InterruptedException
     * @throws IOException
     */
    public static ExecuteMessage execute(Process process, String opName) throws InterruptedException, IOException {
        ExecuteMessage executeMessage = new ExecuteMessage();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        int exitCode = process.waitFor();
        executeMessage.setExitCode(exitCode);
        if (exitCode == 0) {
            System.out.println(opName + "成功");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder compileOutputStringBuilder = new StringBuilder();
            String compileOutputLine;
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileOutputStringBuilder.append(compileOutputLine);
            }
            executeMessage.setMessage(compileOutputStringBuilder.toString());
        } else {
            System.out.println(opName + "编译失败，错误码：" + exitCode);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder compileOutputStringBuilder = new StringBuilder();
            String compileOutputLine;
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileOutputStringBuilder.append(compileOutputLine);
            }
            BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));
            StringBuilder errorCompileOutputStringBuilder = new StringBuilder();
            String errorCompileOutputLine;
            while ((errorCompileOutputLine = errorBufferedReader.readLine()) != null) {
                errorCompileOutputStringBuilder.append(errorCompileOutputLine);
            }
            executeMessage.setErrorMessage(errorCompileOutputStringBuilder.toString());
        }
        stopWatch.stop();
        executeMessage.setTime(stopWatch.getTotalTimeMillis());
        return executeMessage;
    }

}